package org.iweb.classloader;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

public class IWebClassLoader extends URLClassLoader{


	//Set<Class> classLoaded=new HashSet<>();
	private static String base=System.getProperty("catalina.base")+"/webapps/iweb/WEB-INF/lib";
	
    public IWebClassLoader(ClassLoader parent) {
    	
    	super(new URL[0], parent);
    	reload();
    }
    
    protected void reload(){
    	
    	File[] jars=new File(base).listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".jar");				
			}
		});
    	
    	for(File jar: jars){    		
    		try {
				ClassLoaderUtil.addURL(jar.toURI().toURL(), this);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {    	
    	//if(name.startsWith("java."))
    		return super.loadClass(name);
    	
    }
    

//    @SuppressWarnings({ "rawtypes", "unchecked" })
//	public Class loadClass(String name) throws ClassNotFoundException {
//    	if(name.startsWith("java."))
//    		return super.loadClass(name);
//
//        try {
//        	
//            String url = "file:/Users/dmac/Documents/workspace/ee_4_3/TestClassReload/build/classes/org/prj/MyObject.class";
//            URL myUrl = new URL(url);
//            URLConnection connection = myUrl.openConnection();
//            InputStream input = connection.getInputStream();
//            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
//            int data = input.read();
//
//            while(data != -1){
//                buffer.write(data);
//                data = input.read();
//            }
//
//            input.close();
//
//            byte[] classData = buffer.toByteArray();
//
//            
//            
//            return defineClass(name,
//                    classData, 0, classData.length);
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace(); 
//        }
//
//        return null;
//    }

}